package com.hitqz.robot.biz.flow.controller;

import com.hitqz.robot.biz.flow.domain.common.ResponseResult;
import com.hitqz.robot.biz.flow.domain.dto.AddChainDto;
import com.hitqz.robot.biz.flow.domain.dto.ExecuteChainDto;
import com.hitqz.robot.biz.flow.domain.dto.NodeDto;
import com.hitqz.robot.biz.flow.service.LiteFlowService;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.flow.FlowBus;
import com.yomahub.liteflow.flow.element.Node;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 流程控制器
 *
 * @author wengyx
 * @date 2023/08/22
 */
@RestController
@Slf4j
@AllArgsConstructor
@RequestMapping("/flow/controller")
public class FlowController {

    @Resource
    private final FlowExecutor flowExecutor;

    private final LiteFlowService liteFlowService;


    @PostMapping("/chains")
    public ResponseResult<?> addChain(@RequestBody AddChainDto dto) {
        return liteFlowService.setChain(dto.getChainId(),dto.getEl());
    }

    @DeleteMapping("/chains/{chainId}")
    public ResponseResult<?> deleteChain(@PathVariable("chainId") String chainId) {
        if (FlowBus.removeChain(chainId)) {
            return ResponseResult.success();
        }
        return ResponseResult.fail();
    }

    @PutMapping("/chains")
    public ResponseResult<?> updateChain(@RequestBody AddChainDto dto) {
        return ResponseResult.success(liteFlowService.setChain(dto.getChainId(),dto.getEl()));
    }

    @PostMapping("/chains/execute")
    public ResponseResult<?> executeChain(@RequestBody ExecuteChainDto dto) {
        return liteFlowService.executeChain(dto.getChainId(),1);
    }

    @GetMapping("/chains")
    public ResponseResult<?> queryChain() {
        return ResponseResult.success(liteFlowService.getChainsList());
    }

    @GetMapping("/nodes")
    public ResponseResult<?> queryNode() {
        Map<String, Node> nodeMap = FlowBus.getNodeMap();
        List<NodeDto> list = nodeMap.keySet().stream().map(k -> NodeDto.convertNode2Dto(nodeMap.get(k))).collect(Collectors.toList());
        log.info("node：{}",list);
        return ResponseResult.success(list);
    }



}
